import 'package:activity_record/model/data_base.dart';
import 'package:flutter/material.dart';
import 'dart:async';

class MonthAnalysis {
  /*
  这里是你想展示的统计的内容，我们这里自己定义了这么几个，一看就明白了，你可以按照自己想看的内容自定义。
  */
  String _month; //月份
  String _nums; //场次
  String _sumProfit; //总利润
  String _sumTotalAmount; //总流水
  String _sumUnPaidAmount; //总欠款

  MonthAnalysis(this._month, this._nums, this._sumTotalAmount, this._sumProfit,
      this._sumUnPaidAmount);

  MonthAnalysis.fromMap(Map<String, dynamic> map) {
    _month = '${map['month']}月';
    _nums = map['nums'].toString();
    _sumTotalAmount = map['sumTotalAmount'].toString();
    _sumProfit = map['sumProfit'].toString();
    _sumUnPaidAmount = map['sumUnPaidAmount'].toString();
  }
}

class DiyDataAnalysis extends StatefulWidget {
  DiyDataAnalysis(this._db);
  final DataBase _db;

  @override
  State<StatefulWidget> createState() => new DiyDataAnalysisState(this._db);
}

class DiyDataAnalysisState extends State<DiyDataAnalysis> {
  DiyDataAnalysisState(this._database);
  DataBase _database;
  //数据存放查询结果
  List<MonthAnalysis> listItems = [];
  //初始化总金额是0
  String _totalAmount = '0';
  //初始化总利润是0
  String _profit = '0';
  //初始化总欠款是0
  String _unPaidAmount = '0';

  @override
  void initState() {
    super.initState();
    //每次页面初始化的时候进行数据查询用于展示
    _queryAll();
    _queryTotalAmount();
    _queryProfit();
    _queryUnPaidAmount();
  }

  //按月查询数据并生成月分析数据包
  _queryAll() async {
    listItems = [];
    var result = await _database.queryAll();
    setState(() {
      result.forEach((value) {
        listItems.add(MonthAnalysis.fromMap(value));
      });
    });
  }

  //计算所有营收
  _queryTotalAmount() async {
    var result = await _database.queryTotalAmount();
    if (result != null) {
      setState(() {
        _totalAmount = result.toString();
      });
    }
  }

  //计算所有利润
  _queryProfit() async {
    var result = await _database.queryProfit();
    if (result != null) {
      setState(() {
        _profit = result.toString();
      });
    }
  }

  //计算所有欠款
  _queryUnPaidAmount() async {
    var result = await _database.queryUnPaid();
    if (result != null) {
      setState(() {
        _unPaidAmount = result.toString();
      });
    }
  }

  //下拉刷新数据
  Future _refreshData() async {
    _queryAll();
    _queryTotalAmount();
    _queryProfit();
    _queryUnPaidAmount();
  }

  @override
  Widget build(BuildContext context) {
    //上半部分整体统计封装
    Widget _analysisTotal() {
      return Padding(
        padding: const EdgeInsets.fromLTRB(0.0, 48.0, 0.0, 48.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            new Text(
              '活动总额',
              style: new TextStyle(fontSize: 20.0, color: Colors.white),
            ),
            new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text(
                  _totalAmount,
                  style: Theme.of(context)
                      .textTheme
                      .display1
                      .copyWith(color: Colors.white),
                ),
                new Text('  元', style: new TextStyle(color: Colors.white)),
              ],
            ),
            new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Row(
                  children: <Widget>[
                    new Text('利润', style: new TextStyle(color: Colors.white)),
                    new SizedBox(
                      width: 15.0,
                    ),
                    new Text(
                      _profit,
                      style: Theme.of(context)
                          .textTheme
                          .title
                          .copyWith(color: Colors.white),
                    ),
                  ],
                ),
                new SizedBox(
                  width: 30.0,
                  child: new Text(
                    '|',
                    style: new TextStyle(color: Colors.white),
                    textAlign: TextAlign.center,
                  ),
                ),
                new Row(
                  children: <Widget>[
                    new Text('未结', style: new TextStyle(color: Colors.white)),
                    new SizedBox(
                      width: 15.0,
                    ),
                    new Text(
                      _unPaidAmount,
                      style: Theme.of(context)
                          .textTheme
                          .title
                          .copyWith(color: Colors.white),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      );
    }

    //sizedbox封装
    Widget _sizedBox(String text) {
      return new SizedBox(
          width: 45.0,
          child: new Text(
            text,
            textAlign: TextAlign.center,
          ));
    }

    //月统计区域的每一行封装
    Widget _containerShow(MonthAnalysis monthAnalysis) {
      return new Container(
        padding: const EdgeInsets.fromLTRB(0.0, 8.0, 0.0, 8.0),
        decoration: new BoxDecoration(
            border: Border(bottom: new BorderSide(color: Colors.grey[200]))),
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            _sizedBox(monthAnalysis._month),
            _sizedBox(monthAnalysis._nums),
            _sizedBox(monthAnalysis._sumTotalAmount),
            _sizedBox(monthAnalysis._sumProfit),
            _sizedBox(monthAnalysis._sumUnPaidAmount),
          ],
        ),
      );
    }

    //自定义appbar
    Widget _analysisBar() {
      return new Stack(
        children: <Widget>[
          new Container(
            height: 260.0,
            decoration: new BoxDecoration(
                gradient: new LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              // colors: [Color(0xff863e2d), Color(0xFFe6bcb3)],
              colors: [Theme.of(context).accentColor,Theme.of(context).accentColor.withOpacity(0.4)]
            )),
            child: _analysisTotal(),
          ),
          new AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0.0,
            actions: <Widget>[
              new FlatButton(
                onPressed: () {},
                child: new Text(
                  '2019年',
                  style: new TextStyle(color: Colors.white),
                ),
              )
            ],
          )
        ],
      );
    }

    return new Scaffold(
      body: new Stack(
        children: <Widget>[
          _analysisBar(),
          new Padding(
            padding: const EdgeInsets.only(top: 210.0),
            child: new Card(
              margin: const EdgeInsets.all(8.0),
              child: new Column(
                children: <Widget>[
                  new Container(
                    padding: const EdgeInsets.fromLTRB(0.0, 4.0, 0.0, 4.0),
                    decoration: new BoxDecoration(
                        border: new Border(
                            bottom: new BorderSide(color: Colors.grey))),
                    child: new Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        _sizedBox('月份'),
                        _sizedBox('场次'),
                        _sizedBox('营收'),
                        _sizedBox('利润'),
                        _sizedBox('未结'),
                      ],
                    ),
                  ),
                  new Flexible(
                    child: new RefreshIndicator(
                      onRefresh: _refreshData,
                      child: new ListView(
                        padding: EdgeInsets.zero,
                        children: listItems.map((listItem) {
                          return _containerShow(listItem);
                        }).toList(),
                      ),
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
